<template>
  <div class="Role">
    <div class="page-head">
      <div class="page-title">
        角色列表
      </div>
      <div class="page-tool">
        <div v-if="$permiss(btnPermiss, '新增')" class="tool-btn" @click="open('add')">新 增</div>
      </div>
      
    </div>
    <div class="page-body">
      <div class="table_data">
        <el-scrollbar class="scroll-bar">
          <el-table :data="tableData" stripe :fit="true">
            <el-table-column
              width="20"
            />
            <el-table-column
              prop="name"
              label="角色名称"
              :show-overflow-tooltip="true"
              width="480"
            >
            </el-table-column>
            
            <el-table-column prop="remark" label="备注"  :show-overflow-tooltip="true">

            </el-table-column>
            
            <el-table-column label="操作" width="100" align="center">
              <template slot-scope="{row}">
                <div class="operation-col">
                  <div
                    v-if="$permiss(btnPermiss, '修改')"
                    class="txt-btn ope-btn"
                    :disabled="row.reserve == 1"
                    :class="{'primary': row.reserve == 0, 'grey notAllow': row.reserve == 1 }"
                    @click="open('edit', row)"
                  >
                    修改
                  </div>
                  <div
                    v-if="$permiss(btnPermiss, '删除')"
                    class="txt-btn"
                    :disabled="row.reserve == 1"
                    :class="{'error': row.reserve == 0, 'grey notAllow': row.reserve == 1 }"
                    @click="doDelete(row)"
                  >
                    删除
                  </div>
                </div>    
              </template>
            </el-table-column>
          </el-table>
        </el-scrollbar>
      </div>
      <div class="page-footer">
        <pagina-tion
        class="page-pager"
        v-show="total>=0"
        :background="true"
        :total="total"
        :offset.sync="offset"
        :limit.sync="limit"
        @pagination="getChangePage"
      />
      <button class="page-button">确定</button>

      </div>
      
    </div>

    <el-dialog :visible.sync="model.visible" width="450px" :title="model.type =='add' ? '新增角色': '修改角色'" :show-close="false" :close-on-click-modal="false">
      <div class="dialog-body">
        <el-form ref="form" :model="form" label-width="90px" label-position="left">
          <el-form-item label="角色名称" class="required">
            <el-input
              v-model="form.name"
              name="roleName"
              v-validate="'required|roleName'"
              placeholder="请输入角色名称"
            />
            <div v-show="errors.has('roleName')" class="el-form-item__error">{{ errors.first('roleName') }}</div>
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              maxlength="128"
              v-model.trim="form.remark"
            />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="close">取 消</el-button>
        <el-button type="primary" @click="setPermission">设置权限</el-button>
      </span>
    </el-dialog>
    <!-- 设置权限 -->
    <el-dialog :show-close="true"  :visible.sync="permissionModel.setVisable" width="1100px" :title="permissionModel.type =='add' ? '设置权限': '修改权限'"  :close-on-click-modal="false" >
      <div v-if="menu.length > 0" class="dialog-body">
        <el-table :data="menu" :fit="true">
          <el-table-column prop="txt" label="菜单名称" width="100"  align="center"></el-table-column>
          <el-table-column label="是否可见" prop="checked" align="center" width="140">
            <template slot-scope="scope">
              <div @click="changeState(scope.row, scope.$index)" class="checkIcon">
                <img v-if="scope.row.checked" key="checkRed" src="~assets/img/checkRed.png">
                <img v-else key="checkGray" src="~assets/img/check.png">
              </div>
            </template>
          </el-table-column>
           <el-table-column prop="txt" label="按钮是否可见" align="left">
              <template slot-scope="{row}">
                <div class="permission-flex">
                  <el-checkbox v-for="(b, i) in row.btns" v-model="b.checked" :key="i">
                    {{b.txt}}
                  </el-checkbox>

                </div>
            </template>
           </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="goBackStep">上一步</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 删除弹窗 -->
    <el-dialog
      :visible.sync="visibility"
      width="430px"
      height="100px"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="dialog-content comfirm-body">
        <img class="comfirm-ico"
             src="~assets/img/warning.png">
        <div class="comfirm-txt">
          <div>
            确定删除该条角色？
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="visibility = false">取 消</el-button>
        <el-button type="primary" @click="roleDelete">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as api from '@/api'
import { limit,middleLimit } from '@/consts/consts'
import { roleFormKey } from '@/consts/formKey'
export default {
  data() {
    return {
      btnPermiss: [],
      limit:document.body.clientHeight>= 1366 ? limit : middleLimit,
      total: 0,
      offset: 0,
      tableData: [],
      setVisable: false,
      form: {...roleFormKey},
      model: {
        type: 'add',
        visible: false
      },
      // 设置权限
      permissionModel:{
        type: 'add',
        setVisable: false

      },
      radio:'',
      menu: JSON.parse(localStorage.getItem("permission")) || [],
      role_id: '',
      visibility: false,
      addChecked: true,
      editChecked: true,

    }
  },
  methods: {
    open(type, row=null) {
      this.$validator.reset()
      this.model.type = type
      this.permissionModel.type = type
      if (row) {
        if (row.reserve == 1) {
          return this.$message.warning('无修改权限')
        }
        for (const k in roleFormKey) {
          this.form[k] = row[k]
        }
        this.role_id = row.role_id
        this.menu = JSON.parse(row.permission)
      }
      this.model.visible = true
    },
    getChangePage(val) {
      this.offset = val.offset
      this.roleList()
    },

    changeState(row,index){
      row.checked = !row.checked
      
      row.btns?.forEach(b => {
        b.checked = row.checked
      })
      
    },

    // 设置权限
    setPermission(){
      this.$validator.validateAll().then(valid=>{
        if(valid){
          this.model.visible = false
          this.permissionModel.setVisable = true
        }
      })

    },


    // 返回上一步
    goBackStep(){
      this.permissionModel.setVisable  = false
      this.model.visible = true
    },
    close() {
      this.model.visible = false
      this.form = {...roleFormKey}
    },
    submit() {
      this.$validator.validateAll().then(valid => {
        if (valid) {
          this.addOrEdit()
        } else {
          this.$message.warning('有信息未填写正确')
        }
      })
      
    },
    doDelete(row){
      if(row.reserve === 1) {
        return this.$message.warning('无删除权限')
      }
      this.role_id = row.role_id
      this.visibility = true

    },


    async roleList() {
      const { code, data, total } = await api.role(this).roleList({
        offset: this.offset,
        limit:this.limit
      })
      if (code === 0) {
        this.tableData = data

        this.total = total
      }
    },
      
    async addOrEdit() {
      let fn = this.model.type === 'add' ? 'roleAdd' : 'roleUpdate'
      this.form.permission = JSON.stringify(this.menu)
      console.log('pe: ', this.form.permission)
      const { code, data } = await api.role(this)[fn](this.form,this.role_id)
      if (code === 0) {
        if(this.model.type === "add" && this.permissionModel.type === "add"){
          this.menu = JSON.parse(localStorage.getItem("permission")) // 返回最初的状况)
        }
        this.$message.success('操作成功')
        this.form.name = ''
        this.permissionModel.setVisable = false
        this.model.visible = false
        this.close()
        this.roleList()
      }
    },
    
    async roleDelete() {
      const { code } = await api.role(this).roleDelete(this.role_id)
      if (code === 0) {
        this.$message.success('操作成功')
        this.role_id = ''
        this.visibility = false
        this.roleList()
      }
    },
  },
  created () {
    let curMenu = this.menu.find(item => item.txt === "角色管理")
    this.btnPermiss = curMenu.btns
    this.roleList()
    
  },
}
</script>

<style lang="stylus">
.Role {

  .checkIcon {
    cursor: pointer;
  }
}
</style>